package net.esj.basic.plugins.struts2.interceptor;

import javax.servlet.http.HttpServletRequest;

import net.esj.basic.core.engine.config.MelonConfig;
import net.esj.basic.core.view.tools.ActionContext;
import net.esj.basic.plugins.view.FacadeAware;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class FacadeInterceptor extends AbstractInterceptor {

	private Configuration strutsConfig;
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Object o = invocation.getAction();
		//PackageConfig pconfig = strutsConfig.getPackageConfig(packagename);
		if(o instanceof FacadeAware){
			FacadeAware aware = (FacadeAware) o;
			aware.setTemplate(MelonConfig.getProperty(FacadeAware.VIEW_TEMPALTE_KEY,FacadeAware.VIEW_TEMPALTE_DEFAULT));
			aware.setTheme(MelonConfig.getProperty(FacadeAware.VIEW_THEME_KEY, FacadeAware.VIEW_THEME_DEFAULT));
			//aware.setNamespace(pconfig.getNamespace());
			aware.setNamespace(invocation.getProxy().getNamespace());
			//aware.setNamespace(resolveNamespace(((HttpServletRequest)ActionContext.getRequest()).getRequestURI()));
		}
		return invocation.invoke();
	}

	@Inject
	public void setStrutsConfig(Configuration strutsConfig) {
		this.strutsConfig = strutsConfig;
	}

	private String resolveNamespace(String uri){
		int splash = uri.lastIndexOf("/");
		if(splash<=0){
			return "";
		}else{
			return uri.substring(0, splash);
		}
	}
}
